package actor.atLeastoncedelivery

import actor.atLeastoncedelivery.Calculator._
import akka.actor.{Actor, ActorLogging, Props}

import scala.util.Random

/**
 * Created by DJJ on 2019/12/29.
 */
object Calculator {
  sealed trait Math
  case class Add(id:Long ,x:Int,y:Int) extends Math
  case class Sub(id:Long ,x:Int,y:Int) extends Math
  case class Mul(id:Long ,x:Int,y:Int) extends Math
  case class Div(id:Long ,x:Int,y:Int) extends Math

  case class Ack(id:Long,x:Int)
  case class CalcMatch(expr:Math)

  def props=Props(new Calculator)
}
class Calculator extends Actor  with ActorLogging{

  import scala.concurrent.duration._
  import context.dispatcher
  override def receive: Receive = {
    case CalcMatch(expr)=>{
      val delay: FiniteDuration = (100 millis)*Random.nextInt(10)
      context.system.scheduler.scheduleOnce(delay,self,expr)
    }
    case add: Add => sender() ! Ack(add.id,add.x + add.y)
    case sub: Sub => sender() ! Ack(sub.id,sub.x - sub.y)
    case mul: Mul => sender() ! Ack(mul.id,mul.x * mul.y)
    case div: Div => sender() ! Ack(div.id,div.x / div.y)
  }
}